package com.example.springboot.dao.imp;

import com.example.springboot.bean.UserAccount;
import com.example.springboot.dao.UserAccountDao;
import com.example.springboot.exception.OutofMoneyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by tang on 2018/3/8.
 */
@Service
public class UserAccountDaoImpl implements UserAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserAccount findByName(String name) {
        RowMapper<UserAccount> rowMapper = new BeanPropertyRowMapper<UserAccount>(UserAccount.class);
        String sql = "select id,customer_name,balance from  book_user_account where customer_name=?";

        return jdbcTemplate.queryForObject(sql, new String[]{name}, rowMapper);
    }

    @Override
    @Transactional
    public void updateUserAccount(double costMoney, String name) {
        String sql = "select balance from book_user_account where customer_name=?";
        double balance = jdbcTemplate.queryForObject(sql, new String[]{name}, Double.class);
        if (balance - costMoney > 0.0) {
            sql = "update book_user_account set balance=balance-? where customer_name=?";
            jdbcTemplate.update(sql, costMoney, name);
        } else {
            throw new OutofMoneyException("OUT_OF_MONEY");
        }
    }


}
